# -*- coding: utf-8 -*-

import os
import cgi
import sys
import logging

from datetime import datetime
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.db import Key 
from google.appengine.ext.webapp import template
from google.appengine.api import users
from django.utils import simplejson
from google.appengine.api import images


from baseclass import BaseHandler
from model import Stuff99

class Stuff99List(BaseHandler):
    def get(self):
        template_values = {}
        self.outputTemplate(template_values, "stuff99_list_view.html") 
        
class Stuff99ProfileAdd(BaseHandler):
    def get(self):
        if self.request.get('person'):
            template_values = {'who':self.request.get('person')}
        else:
            template_values = {'msg':'n/a'}
        self.outputTemplate(template_values, "stuff99_profile_add_view.html")
    
    def post(self):
        if self.request.get('who'):
            query = db.Query(Stuff99)
            query.filter('who =', self.request.get('who')).filter('what =', self.request.get('what'))
            stuff = query.get()
            if stuff:
                tempalte_values = {'msg':'You have bought this already.'}
            else:
                stuff = Stuff99()
                stuff.who = self.request.get('who')
                stuff.what = self.request.get('what')
                stuff.comment = self.request.get('comment')
                stuff.price = float(self.request.get('price'))
                stuff.rating = int(self.request.get('rating'))
                stuff.uri = self.request.get('uri')
                stuff.put()
                template_values = {'msg':'ok'}
        else:
            template_values = {'msg':'error'}
        self.outputTemplate(template_values, "stuff99_profile_add_view.html")        
    
class Stuff99ProfileMain(BaseHandler):
    def post(self):
        if self.request.get('items'):
            items = simplejson.loads(self.request.get('items'))
            html = []
            for item in items:
                # skip some system ids
                if item['id'] == '1300000001@myspace':
                    continue
                if item['id'] == '1300200888@myspace':
                    continue
                query = db.Query(Stuff99)
                query.filter('who =', item['id'])
                bought = query.get()                
                if bought:
                    html.append("<div>%(who)s bought %(what)s</div>" % {'who':item['name'], 'what':bought.what})
                else:
                    html.append("<div>%s bought nothing</div>" % item['name'])
                #html.append(item['name'])
            template_values = {'items':html}
        else:
            template_values = {'msg':'n/a'}
        self.outputTemplate(template_values, "stuff99_profile_main_view.html")  
        
class ImageDisplay(BaseHandler):
    def get(self):
        try:
            imgs = {}
            token = str(abs(hash(self.request.get('token')+"cool")))
            logging.debug("token: "+token)
            for i in [0,1,2,3,4,5]:
                title = token[i]
                query = db.Query(Stuff99)
                query.filter("what =", title)
                img = query.get()
                if img:
                    imgs[i] = img.picture
                else:
                    raise "not found"+title
            composite = images.composite([(imgs[0],0,0,1.0,0), 
                                          (imgs[1],20,0,0.8,0),
                                          (imgs[2],40,0,0.7,0),
                                          (imgs[3],60,0,0.6,0),
                                          (imgs[4],80,0,0.5,0),
                                          (imgs[5],100,0,0.4,0)
                                          ]
                                         , 300, 50)
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(composite)
        except:
            template_values = {'msg': str(sys.exc_info())}
            self.outputTemplate(template_values, "stuff99_profile_main_view.html")

class ImageList(BaseHandler):
    def get(self):
        template_values = {}
        try:
            query = db.Query(Stuff99)
            query.order('what')
            items = query.fetch(99)
            template_values['items'] = items
        except:
            template_values['msg'] = str(sys.exc_info())
        finally:
            self.outputTemplate(template_values, "stuff99_view.html")
            
        
class ImageAdd(BaseHandler):
    def get(self):
        self.response.out.write("""
          <form action="/stuff99/img/add" enctype="multipart/form-data" method="post">
            <div><label>Title:</label></div>
            <div><input type="text" name="title"></input></div>
            <div><label>Image:</label></div>
            <div><input type="file" name="img"/></div>
            <div><input type="text" name="secret"/></div>
            <div><input type="submit" value="Submit"></div>
          </form>
        </body>
      </html>""")
        
    def post(self):
        template_values = {}
        try:
            if self.request.get('secret') != "cool":
                raise "secret"
            img =  Stuff99()
            img.what = self.request.get('title')
            png = self.request.get('img')
            img.picture = db.Blob(png)        
            img.put()
            template_values['msg'] = 'OK'
        except:
            template_values['msg'] = 'Error'
        self.outputTemplate(template_values, "stuff99_view.html")
        
application = webapp.WSGIApplication(
                                     [('/stuff99/list', Stuff99List),
                                      ('/stuff99/profile/main', Stuff99ProfileMain),
                                      ('/stuff99/profile/add', Stuff99ProfileAdd),
                                      ('/stuff99/img/display', ImageDisplay),
                                      ('/stuff99/img/add', ImageAdd),
                                      ('/stuff99/img/list', ImageList)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
    